//
// Created by inter on 2019-10-15.
//

#include "machine_info.h"

#include <signal.h>
#include <cstdlib>
#include <cstdio>
#include <fstream>
#include <unistd.h>
#include <netinet/in.h>
#include <sstream>
#include <cstring>
#include <net/if.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <linux/hdreg.h>
#include <scsi/sg.h>


#define cpuid(func, eax, ebx, ecx, edx)\
    __asm__ __volatile__ ("cpuid":\
    "=a" (eax),"=b" (ebx),"=c" (ecx),"=d" (edx):\
    "a" (func));


static int execCMD(const char *cmd) {
    if (!cmd)
        return -1;

    sighandler_t old_handler;
    old_handler = signal(SIGCHLD, SIG_DFL);
    int ret = system(cmd);
    signal(SIGCHLD, old_handler);
    return ret;
}

static bool checkVirtualBySystemd() {
    const char *virtual_result = ".virtual_result.txt";
    char command[512] = {0};
    snprintf(command, sizeof(command), "systemd-detect-virt > %s", virtual_result);

    std::string res;
    if (0 == execCMD(command)) {
        std::ifstream ifs(virtual_result, std::ios::in | std::ios::binary);
        char line[1024] = {0};
        ifs.getline(line, sizeof(line));
        ifs.close();
        res += line;
    }

    unlink(virtual_result);
    return (!res.empty());
}

static bool checkVirtualByVirt() {
    const char *virtual_result = ".virtual_result.txt";
    char command[512] = {0};
    snprintf(command, sizeof(command), " virt-what > %s", virtual_result);

    std::string res;
    if (0 == execCMD(command)) {
        std::ifstream ifs(virtual_result, std::ios::in | std::ios::binary);
        char line[1024] = {0};
        ifs.getline(line, sizeof(line));
        ifs.close();
        res += line;
    }

    unlink(virtual_result);
    return (!res.empty());
}

static bool getCpuIdByAsm(string &cpu_id) {
    cpu_id.clear();

    unsigned int s1 = 0;
    unsigned int s2 = 0;
    asm volatile
    (
    "movl $0x01, %%eax; \n\t"
    "xorl %%edx, %%edx; \n\t"
    "cpuid; \n\t"
    "movl %%edx, %0; \n\t"
    "movl %%eax, %1; \n\t"
    : "=m"(s1), "=m"(s2)
    );

    if (0 == s1 && 0 == s2) {
        return (false);
    }

    char cpu[32] = {0};
    snprintf(cpu, sizeof(cpu), "%08X%08X", htonl(s2), htonl(s1));

    std::stringstream ss;
    ss << cpu;
    ss >> cpu_id;

    //std::string(cpu).swap(cpu_id);
    return (true);
}

static void parseCpuId(const char *file_name, const char *match_words, std::string &cpu_id) {
    cpu_id.clear();

    std::ifstream ifs(file_name, std::ios::binary);
    if (!ifs.is_open()) {
        return;
    }

    char line[4096] = {0};
    while (!ifs.eof()) {
        ifs.getline(line, sizeof(line));
        if (!ifs.good()) {
            break;
        }

        const char *cpu = strstr(line, match_words);
        if (nullptr == cpu) {
            continue;
        }
        cpu += strlen(match_words);

        while ('\0' != cpu[0]) {
            if (' ' != cpu[0]) {
                cpu_id.push_back(cpu[0]);
            }
            ++cpu;
        }

        if (!cpu_id.empty()) {
            break;
        }
    }

    ifs.close();
}

static bool getCpuIdBySystem(std::string &cpu_id) {
    cpu_id.clear();

    const char *dmidecode_result = ".dmidecode_result.txt";
    char command[512] = {0};
    snprintf(command, sizeof(command), "dmidecode -t 4 | grep ID > %s", dmidecode_result);

    if (0 == execCMD(command)) {
        parseCpuId(dmidecode_result, "ID:", cpu_id);
    }

    unlink(dmidecode_result);

    return (!cpu_id.empty());
}

bool getMacAddressByIoctl(std::string &mac_address) {
    mac_address.clear();

    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0) {
        return (false);
    }

    struct ifreq ifr = {0};
    strncpy(ifr.ifr_name, "eth0", sizeof(ifr.ifr_name) - 1);
    bool ret = (ioctl(sock, SIOCGIFHWADDR, &ifr) >= 0);

    close(sock);

    const char hex[] =
            {
                    '0', '1', '2', '3', '4', '5', '6', '7',
                    '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
            };
    char mac[16] = {0};
    for (int index = 0; index < 6; ++index) {
        size_t value = (size_t) ifr.ifr_hwaddr.sa_data[index] & 0xFF;
        mac[2 * index + 0] = hex[value / 16];
        mac[2 * index + 1] = hex[value % 16];
    }
    std::string(mac).swap(mac_address);

    return (ret);
}

static void parseMacAddress(const char *file_name, const char *match_words, std::string &mac_address) {
    mac_address.clear();

    std::ifstream ifs(file_name, std::ios::binary);
    if (!ifs.is_open()) {
        return;
    }

    char line[4096] = {0};
    while (!ifs.eof()) {
        ifs.getline(line, sizeof(line));
        if (!ifs.good()) {
            break;
        }

        const char *mac = strstr(line, match_words);
        if (nullptr == mac) {
            continue;
        }
        mac += strlen(match_words);

        while ('\0' != mac[0]) {
            if (' ' != mac[0] && ':' != mac[0]) {
                mac_address.push_back(mac[0]);
            }
            ++mac;
        }

        if (!mac_address.empty()) {
            break;
        }
    }

    ifs.close();
}

static bool getMacAddressBySystem(std::string &mac_address) {
    mac_address.clear();

    const char *lshw_result = ".lshw_result.txt";
    char command[512] = {0};
    snprintf(command, sizeof(command), "lshw -c network | grep serial | head -n 1 > %s", lshw_result);

    if (0 == execCMD(command)) {
        parseMacAddress(lshw_result, "serial:", mac_address);
    }

    unlink(lshw_result);

    return (!mac_address.empty());
}

static void parseBoardSerial(const char *file_name, const char *match_words, std::string &board_serial) {
    board_serial.clear();

    std::ifstream ifs(file_name, std::ios::binary);
    if (!ifs.is_open()) {
        return;
    }

    char line[4096] = {0};
    while (!ifs.eof()) {
        ifs.getline(line, sizeof(line));
        if (!ifs.good()) {
            break;
        }

        const char *board = strstr(line, match_words);
        if (nullptr == board) {
            continue;
        }
        board += strlen(match_words);

        while ('\0' != board[0]) {
            if (' ' != board[0]) {
                board_serial.push_back(board[0]);
            }
            ++board;
        }

        if ("None" == board_serial) {
            board_serial.clear();
            continue;
        }

        if (!board_serial.empty()) {
            break;
        }
    }

    ifs.close();
}

static bool getBoardSerialBySystem(std::string &board_serial) {
    board_serial.clear();

    const char *dmidecode_result = ".dmidecode_result.txt";
    char command[512] = {0};
    snprintf(command, sizeof(command), "dmidecode -t 2 | grep Serial > %s", dmidecode_result);

    if (0 == execCMD(command)) {
        printf("44444444\n");
        parseBoardSerial(dmidecode_result, "Serial Number:", board_serial);
    }

    unlink(dmidecode_result);

    return (!board_serial.empty());
}

static bool get_disk_name(std::string &disk_name) {
    disk_name.c_str();

    std::ifstream ifs("/etc/mtab", std::ios::binary);
    if (!ifs.is_open()) {
        return (false);
    }

    char line[4096] = {0};
    while (!ifs.eof()) {
        ifs.getline(line, sizeof(line));
        if (!ifs.good()) {
            break;
        }

        const char *disk = line;
        while (isspace(disk[0])) {
            ++disk;
        }

        const char *space = strchr(disk, ' ');
        if (nullptr == space) {
            continue;
        }

        const char *mount = space + 1;
        while (isspace(mount[0])) {
            ++mount;
        }
        if ('/' != mount[0] || ' ' != mount[1]) {
            continue;
        }

        while (space > disk && isdigit(space[-1])) {
            --space;
        }

        if (space > disk) {
            std::string(disk, space).swap(disk_name);
            break;
        }
    }

    ifs.close();

    return (!disk_name.empty());
}

static void trimDiskSerial(const void *serial, size_t serial_len, std::string &serial_no) {
    const char *serial_s = static_cast<const char *>(serial);
    const char *serial_e = serial_s + serial_len;
    while (serial_s < serial_e) {
        if (isspace(serial_s[0])) {
            ++serial_s;
        } else if ('\0' == serial_e[-1] || isspace(serial_e[-1])) {
            --serial_e;
        } else {
            break;
        }
    }

    if (serial_s < serial_e) {
        std::string(serial_s, serial_e).swap(serial_no);
    }
}

static bool getDiskSerialByWay1(const std::string &disk_name, std::string &serial_no) {
    serial_no.clear();

    int fd = open(disk_name.c_str(), O_RDONLY);
    if (-1 == fd) {
        return (false);
    }

    struct hd_driveid drive = {0};
    if (0 == ioctl(fd, HDIO_GET_IDENTITY, &drive)) {
        trimDiskSerial(drive.serial_no, sizeof(drive.serial_no), serial_no);
    }

    close(fd);

    return (!serial_no.empty());
}

static bool scsi_io(
        int fd, unsigned char *cdb,
        unsigned char cdb_size, int xfer_dir,
        unsigned char *data, unsigned int data_size,
        unsigned char *sense, unsigned int sense_len
) {
    sg_io_hdr_t io_hdr = {0};
    io_hdr.interface_id = 'S';
    io_hdr.cmdp = cdb;
    io_hdr.cmd_len = cdb_size;
    io_hdr.sbp = sense;
    io_hdr.mx_sb_len = sense_len;
    io_hdr.dxfer_direction = xfer_dir;
    io_hdr.dxferp = data;
    io_hdr.dxfer_len = data_size;
    io_hdr.timeout = 5000;

    if (ioctl(fd, SG_IO, &io_hdr) < 0) {
        return (false);
    }

    if (SG_INFO_OK != (io_hdr.info & SG_INFO_OK_MASK) && io_hdr.sb_len_wr > 0) {
        return (false);
    }

    if (io_hdr.masked_status || io_hdr.host_status || io_hdr.driver_status) {
        return (false);
    }

    return (true);
}

static bool getDiskSerialByWay2(const std::string &disk_name, std::string &serial_no) {
    serial_no.clear();

    int fd = open(disk_name.c_str(), O_RDONLY);
    if (-1 == fd) {
        return (false);
    }

    int version = 0;
    if (ioctl(fd, SG_GET_VERSION_NUM, &version) < 0 || version < 30000) {
        close(fd);
        return (false);
    }

    const unsigned int data_size = 0x00ff;
    unsigned char data[data_size] = {0};
    const unsigned int sense_len = 32;
    unsigned char sense[sense_len] = {0};
    unsigned char cdb[] = {0x12, 0x01, 0x80, 0x00, 0x00, 0x00};
    cdb[3] = (data_size >> 8) & 0xff;
    cdb[4] = (data_size & 0xff);

    if (scsi_io(fd, cdb, sizeof(cdb), SG_DXFER_FROM_DEV, data, data_size, sense, sense_len)) {
        int page_len = data[3];
        trimDiskSerial(data + 4, page_len, serial_no);
    }

    close(fd);

    return (!serial_no.empty());
}

static bool parse_serial(const char *line, int line_size, const char *match_words, std::string &serial_no) {
    const char *serial_s = strstr(line, match_words);
    if (serial_s == NULL) {
        return (false);
    }
    serial_s += strlen(match_words);
    while (isspace(serial_s[0])) {
        ++serial_s;
    }

    const char *serial_e = line + line_size;
    const char *comma = strchr(serial_s, ',');
    if (NULL != comma) {
        serial_e = comma;
    }

    while (serial_e > serial_s && isspace(serial_e[-1])) {
        --serial_e;
    }

    if (serial_e <= serial_s) {
        return (false);
    }

    std::string(serial_s, serial_e).swap(serial_no);

    return (true);
}

static void get_serial(const char *file_name, const char *match_words, std::string &serial_no) {
    serial_no.c_str();

    std::ifstream ifs(file_name, std::ios::binary);
    if (!ifs.is_open()) {
        return;
    }

    char line[4096] = {0};
    while (!ifs.eof()) {
        ifs.getline(line, sizeof(line));
        if (!ifs.good()) {
            break;
        }

        if (0 == ifs.gcount()) {
            continue;
        }

        if (parse_serial(line, ifs.gcount() - 1, match_words, serial_no)) {
            break;
        }
    }

    ifs.close();
}

static bool getDiskSerialByWay3(const std::string &disk_name, std::string &serial_no) {
    serial_no.c_str();

    const char *hdparm_result = ".hdparm_result.txt";
    char command[512] = {0};
    snprintf(command, sizeof(command), "hdparm -i %s | grep SerialNo > %s", disk_name.c_str(), hdparm_result);

    if (0 == system(command)) {
        get_serial(hdparm_result, "SerialNo=", serial_no);
    }

    unlink(hdparm_result);

    return (!serial_no.empty());
}

static bool getDiskSerialByWay4(std::string &serial_no) {
    serial_no.c_str();

    const char *lshw_result = ".lshw_result.txt";
    char command[512] = {0};
    snprintf(command, sizeof(command), "lshw -class disk | grep serial > %s", lshw_result);

    if (0 == system(command)) {
        get_serial(lshw_result, "serial:", serial_no);
    }

    unlink(lshw_result);

    return (!serial_no.empty());
}


bool MachineInfo::getCpuId(string &cpu_id) {
    if (getCpuIdByAsm(cpu_id)) {
        return true;
    }

    if (0 == getuid()) {
        if (getCpuIdBySystem(cpu_id)) {
            return true;
        }
    }
    return false;
}

bool MachineInfo::getCpuBrand(string &cpu_brand) {
    unsigned int a, b, c, d, i;
    unsigned int cpu_brand_buf[13];
    int k = 0;

    memset((void *) cpu_brand_buf, 0, sizeof(cpu_brand_buf));
    /**
    * eax == 0x800000000
    * 如果CPU支持Brand String，则在EAX中返 >= 0x80000004的值。
    */
    cpuid(0x80000000, a, b, c, d);
    if (a < 0x80000004) {
        printf("the cpu is not support\n");
        return false;
    }

    for (i = 0x80000002; i <= 0x80000004; i++) {
        cpuid(i, a, b, c, d);
        cpu_brand_buf[k++] = (unsigned int) a;
        cpu_brand_buf[k++] = (unsigned int) b;
        cpu_brand_buf[k++] = (unsigned int) c;
        cpu_brand_buf[k++] = (unsigned int) d;
    }

    cpu_brand = string((char *) cpu_brand_buf, strlen((char *) cpu_brand_buf));
    return true;
}


bool MachineInfo::isVirtualMachine() {
    if (0 == getuid()) {
        if (checkVirtualBySystemd()) {
            return true;
        }

        if (checkVirtualByVirt()) {
            return true;
        }
    }
    return false;
}

bool MachineInfo::getMacAddress(string &mac_address) {
    return getMacAddressByIoctl(mac_address) || getMacAddressBySystem(mac_address);
}

bool MachineInfo::getMainboardSerialNumber(string &board_serial) {
    if (0 == getuid()) {
        if (getBoardSerialBySystem(board_serial)) {
            return true;
        }
    }
    return false;
}

bool MachineInfo::getDiskSerialNumber(std::string &serial_no) {
    if (0 != getuid()) {
        return (false);
    }

    std::string disk_name;
    if (get_disk_name(disk_name)) {
        if (getDiskSerialByWay1(disk_name, serial_no)) {
            return (true);
        }
        if (getDiskSerialByWay2(disk_name, serial_no)) {
            return (true);
        }
        if (getDiskSerialByWay3(disk_name, serial_no)) {
            return (true);
        }
    }

    if (getDiskSerialByWay4(serial_no)) {
        return (true);
    }
    return (false);
}